package com.webservice;

import com.carpark.ejb.DAO.DAO;
import com.carpark.ejb.DAO.DaoImpl;
import com.carpark.ejb.Model.ClientsModel;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.validation.constraints.Size;
import validator.ValidationBean;

/**
 *
 * @author Krzysztof
 */
@ManagedBean
@ViewScoped
public class ClientBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private final DAO dao = getSingleDao();
    ClientsModel currentUser;
    private Integer clientId;
    @Size(min = 1, max = 20)
    private String name;
    @Size(min = 1, max = 50)
    private String lastName;
    @Size(min = 1, max = 30)
    private String city;
    @Size(min = 1, max = 15)
    private String zipCode;
    @Size(min = 1, max = 30)
    private String street;
    @Size(min = 1, max = 15)
    private String houseNumber;
    private Integer localNumber;
    @Size(max = 13)
    private String nipNumber;
    @Size(max = 12)
    private String phone;
    @Size(max = 50)
    private String email;
    @Size(max = 255)
    private String password;
    @Size(max = 100)
    private String comments;
    ValidationBean passwordCoder;
    DaoSingleObject dso;
private boolean mobile_startEdit;

    private LoginBean lg;

    @PostConstruct
    public void init() {
        setCurrentUser(dao.getClientById(getUserID()));
        loadAllValuesFromDatabase();
        mobile_startEdit=false;
    }

    public DAO getDao() {
        return dao;
    }
  public DAO getSingleDao() {
        if (this.dso == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            Application app = context.getApplication();
            this.dso = (DaoSingleObject) app.evaluateExpressionGet(context, "#{daoSingleObject}", DaoSingleObject.class);
        }
        return this.dso.dao;
    }
    public Integer getUserID() {
        if (this.lg == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            Application app = context.getApplication();
            this.lg = (LoginBean) app.evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        }
        return this.lg.getId();
    }

    public void updateClientData(Integer id) {
    }

    public LoginBean getLg() {
        return lg;
    }

    public void setLg(LoginBean lg) {
        this.lg = lg;
    }

    public ClientsModel getCurrentUser() {

        return dao.getClientById(clientId);
    }

    public void setCurrentUser(ClientsModel currentUser) {
        this.currentUser = currentUser;
    }

    public final void loadAllValuesFromDatabase() {
        this.city = currentUser.getCity();
        this.comments = currentUser.getComments();
        this.email = currentUser.getEmail();
        this.houseNumber = currentUser.getHouseNumber();
        this.localNumber = currentUser.getLocalNumber();
        this.name = currentUser.getName();
        this.lastName = currentUser.getLastName();
        this.nipNumber = currentUser.getNipNumber();
        this.street = currentUser.getStreet();
        this.phone = currentUser.getPhone();
        this.zipCode = currentUser.getZipCode();
        this.password = currentUser.getPassword();

    }

    public final void setAllValuesToClient(ClientsModel cl) {
        cl.setCity(city);
        cl.setComments(comments);
        cl.setEmail(email);
        cl.setHouseNumber(houseNumber);
        cl.setLocalNumber(localNumber);
        cl.setName(name);
        cl.setLastName(lastName);
        cl.setNipNumber(nipNumber);
        cl.setStreet(street);
        cl.setPhone(phone);
        cl.setZipCode(zipCode);
        cl.setPassword(password);

    }

    public void updateClient(ActionEvent actionEvent) {

        FacesContext context = FacesContext.getCurrentInstance();
        Logger.getLogger(ClientBean.class.getName()).log(Level.SEVERE, "[CarPark] Updating Client ");

        setAllValuesToClient(currentUser);
        if (dao.updateClient(currentUser) == null) {
            context.addMessage(null, new FacesMessage("Wystąpił błąd", "Nie udało się zmienić danych"));
        } else {
            context.addMessage(null, new FacesMessage("Operacja zakończona sukcesem", "Zmieniono Twoje dane."));
        }
    }

    public boolean isMobile_startEdit() {
        return mobile_startEdit;
    }

    public void setMobile_startEdit(boolean mobile_startEdit) {
        this.mobile_startEdit = mobile_startEdit;
    }

    public void updatePassword(ActionEvent actionEvent) throws NoSuchAlgorithmException {
        String code = codePassword(password);
        this.password = code;
        updateClient(actionEvent);
    }

    public Integer getClientId() {
        return clientId;
    }

    public void setClientId(Integer clientId) {
        this.clientId = clientId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getZipCode() {
        return covertNullToEmpty(zipCode);
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }

    public String getStreet() {
        return covertNullToEmpty(street);
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getHouseNumber() {
        return covertNullToEmpty(houseNumber);
    }

    public void setHouseNumber(String houseNumber) {
        this.houseNumber = houseNumber;
    }

    public Integer getLocalNumber() {
        return localNumber;
    }

    public void setLocalNumber(Integer localNumber) {
        this.localNumber = localNumber;
    }

    public String getNipNumber() {
        return covertNullToEmpty(nipNumber);
    }

    public void setNipNumber(String nipNumber) {
        this.nipNumber = nipNumber;
    }

    public String getPhone() {
        return covertNullToEmpty(phone);
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return covertNullToEmpty(email);
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String covertNullToEmpty(String s) {
        if (s.equals("")) {
            return "brak";
        } else {
            return s;
        }
    }

    private String codePassword(String pass) throws NoSuchAlgorithmException {
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        md.update(pass.getBytes());
        byte byteData[] = md.digest();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }

        return sb.toString();
    }
}
